<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { useCustomerStore, useSystemStore, useDictStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import SalesPicker from '@/components/sales-picker/index.vue';
  import dayjs from 'dayjs';
  import { status } from 'nprogress';

  const modalVisible = ref(false);
  const customerStore = useCustomerStore();
  const systemStore = useSystemStore();
  const dictStore = useDictStore();
  const { loading, setLoading } = useLoading(false);
  const detail = ref<any>({
    follow: {
      statusValue: '1',
    },
  });
  const list = ref<any>([]);
  const searchForm = ref<any>({});
  let oldStatusValue = '0';

  onMounted(async () => {
    fetchList();
    await systemStore.getAreas();
  });

  async function fetchList() {
    setLoading(true);
    list.value = await customerStore.getCustomers(searchForm.value);
    setLoading(false);
  }

  // async function handleRemove(record: any) {
  //   await customerStore.deleteCustomer({ id: record.id });
  //   await fetchList();
  // }

  // function handleAdd() {
  //   detail.value = {};
  //   modalVisible.value = true;
  // }

  function handleEdit(record: any) {
    if (record.follow === null) {
      record.follow = {};
    }
    oldStatusValue = record.follow.statusValue;
    detail.value = record;
    modalVisible.value = true;
  }

  async function handleSave() {
    const newCustomerFollow = {
      id: detail.value.follow.statusValue === oldStatusValue ? detail.value.follow.id : null,
      customerId: detail.value.id,
      electricityConsumption: 0,
      startedAt: detail.value.follow.startedAt,
      endedAt: detail.value.follow.endedAt,
      statusValue: detail.value.follow.statusValue,
    };
    const newCustomer = {
      ...detail.value,
    };
    const follow: any = await customerStore.saveCustomerFollow(newCustomerFollow, false);
    newCustomer.customerFollowId = follow.id;
    await customerStore.saveCustomer(newCustomer);
    await fetchList();
    modalVisible.value = false;
  }

  async function handleSearch() {
    if (searchForm.value.statusValue === '') {
      searchForm.value.statusValue = null;
    }
    await fetchList();
  }

  async function handleReset() {
    searchForm.value = {};
    await fetchList();
  }
</script>

<template>
  <div class="container">
    <breadcrumb :items="['menu.customer.management', 'menu.customer.list']" />
    <a-card>
      <a-form :model="{}" auto-label-width>
        <a-row :gutter="16" :wrap="false">
          <a-col flex="auto" style="padding-right: 16px">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="客户状态">
                  <a-select placeholder="请选择客户状态" v-model="searchForm.statusValue" allow-clear>
                    <a-option :value="item.value" v-for="item in dictStore.getDicts('CustomerStatus')">{{ item.label }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="客户名称">
                  <a-input placeholder="请输入客户名称" v-model="searchForm.companyName"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="所属省份">
                  <a-select placeholder="请选择所属省份" v-model="searchForm.provinceId">
                    <a-option :value="item.id" v-for="item in systemStore.areas">{{ item.name }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="销售员" style="margin-bottom: 0">
                  <sales-picker v-model="searchForm.salesId" />
                </a-form-item>
              </a-col>
              <!-- <a-col :span="16">
                <a-form-item label="创建时间" style="margin-bottom: 0">
                  <a-range-picker v-model="searchForm.createdAt" style="width: 100%" show-time :time-picker-props="{ defaultValue: ['00:00:00', '23:59:59'] }" format="YYYY-MM-DD HH:mm" />
                </a-form-item>
              </a-col> -->
            </a-row>
          </a-col>
          <a-col flex="60px" style="border-left: 1px solid #e5e6eb; padding-left: 16px">
            <a-space direction="vertical" :size="16">
              <a-button type="primary" @click="handleSearch()">搜索</a-button>
              <a-button type="primary" @click="handleReset()">重置</a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
      <a-divider margin="16px"></a-divider>
      <!-- <a-button type="primary" style="margin-bottom: 16px" @click="handleAdd" size="small">新增</a-button> -->
      <a-table :data="list" :loading="loading">
        <template #columns>
          <a-table-column title="序号" :width="80">
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column title="销售员" data-index="salesman.realName"></a-table-column>
          <a-table-column title="客户名称" data-index="companyName"></a-table-column>
          <a-table-column title="所属省份" data-index="provinceId">
            <template #cell="{ record }">
              <div v-if="systemStore.areas.length > 0">
                {{ systemStore.getAreaName(record.provinceId) }}
              </div>
            </template>
          </a-table-column>
          <a-table-column title="客户状态" data-index="statusValue">
            <template #cell="{ record }">
              <a-tag v-if="record.follow" color="arcoblue" :default-checked="true">{{ dictStore.label('CustomerStatus', record.follow?.statusValue) }}</a-tag>
              <div v-else>--</div>
            </template>
          </a-table-column>
          <!-- <a-table-column title="发票税点" data-index="invoiceTax">
            <template #cell="{ record }"> {{ record.invoiceTax }}% </template>
          </a-table-column> -->
          <a-table-column title="开始时间" :width="170">
            <template #cell="{ record }">
              <span v-if="record.follow?.startedAt">{{ dayjs(record.follow?.startedAt).format('YYYY-MM-DD') }}</span>
              <span v-else>--</span>
            </template>
          </a-table-column>
          <a-table-column title="结束时间" :width="170">
            <template #cell="{ record }">
              <span v-if="record.follow?.endedAt">{{ dayjs(record.follow?.endedAt).format('YYYY-MM-DD') }}</span>
              <span v-else>--</span>
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="100">
            <template #cell="{ record }">
              <a-space>
                <a-button type="primary" @click="handleEdit(record)" size="small">编辑</a-button>
                <!-- <a-popconfirm content="您确认移除么?" @ok="handleRemove(record)">
                  <a-button type="primary" status="danger" size="small">移除</a-button>
                </a-popconfirm> -->
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
    <a-modal :visible="modalVisible" :title="detail.id ? '编辑客户' : '新增客户'" @cancel="modalVisible = false" @ok="handleSave">
      <a-form :model="{}" auto-label-width>
        <!-- <a-form-item label="选择销售" required>
          <sales-picker v-model="detail.salesId" :default-account="true" />
        </a-form-item>
        <a-form-item label="客户名称" required>
          <a-input v-model="detail.companyName" placeholder="请输入客户名称" />
        </a-form-item> -->
        <a-form-item label="所属省份" required>
          <a-select placeholder="请选择所属省份" v-model="detail.provinceId">
            <a-option :value="item.id" v-for="item in systemStore.areas">{{ item.name }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="客户状态">
          <a-select placeholder="请选择客户状态" v-model="detail.follow.statusValue">
            <a-option :value="item.value" v-for="item in dictStore.getDicts('CustomerStatus')">{{ item.label }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="开始时间" required>
          <a-date-picker v-model="detail.follow.startedAt" style="width: 100%" placeholder="请选择开始时间" />
        </a-form-item>
        <a-form-item label="结束时间" required>
          <a-date-picker v-model="detail.follow.endedAt" style="width: 100%" placeholder="请选择结束时间" />
        </a-form-item>
        <!-- <a-form-item label="发票税点">
          <a-input-number v-model="detail.invoiceTax" placeholder="请输入发票税点" hide-button>
            <template #suffix> % </template>
          </a-input-number>
        </a-form-item> -->
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
  .container {
    padding: 0 16px;
  }
</style>
